package com.compass.doctor.ui.prescription

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.callback.OnCustomButtonClick
import com.compass.doctor.databinding.ActivityAppendTemplateBinding
import com.compass.doctor.ui.prescription.adapter.PrescriptionDiagnoseAdapter
import com.compass.doctor.ui.prescription.adapter.PrescriptionDrugAdapter
import com.compass.doctor.ui.prescription.viewmodel.PrescribeViewModel
import com.compass.doctor.base.BaseVBActivity
import com.compass.framework.R
import com.compass.framework.constant.KEY_CONSULT_TYPE
import com.compass.framework.constant.KEY_DRUG_LIST
import com.compass.framework.constant.REFRESH_RX_TEMPLATE
import com.compass.framework.decoration.NormalItemDecoration
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.visible
import com.compass.framework.model.Diagnosis
import com.compass.framework.model.Drug
import com.compass.framework.model.PrescriptionInformation
import com.compass.framework.model.TemplateDetails
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.dpToPx
import com.compass.framework.utils.getStringFromResource
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent

/**
 * Description： 新增处方模板
 * Date:2023/12/19 15:23
 */
class AppendTemplateActivity : BaseVBActivity<ActivityAppendTemplateBinding>() {


    companion object {
        fun start(context: Context, id: String?) {
            val intent = Intent(context, AppendTemplateActivity::class.java)
            intent.putExtra("id", id)
            context.startActivity(intent)
        }
    }

    private val prescribeViewModel: PrescribeViewModel by viewModels()
    private var rxInformation: PrescriptionInformation = PrescriptionInformation()
    private var diagnosesList: MutableList<Diagnosis> = mutableListOf()
    private lateinit var prescriptionDiagnoseAdapter: PrescriptionDiagnoseAdapter
    private var drugList: ArrayList<Drug> = ArrayList()
    private lateinit var prescriptionDrugAdapter: PrescriptionDrugAdapter
    private var requestType: Int = 1
    private var diagnosis: Diagnosis? = null//接收返回的诊断数据/检验检查
    private var rxId: String? = null//处方模板id


    //诊断回调
    private val mActivityResultLauncherDiagnosis: ActivityResultLauncher<Intent>? =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK) {
                it.data?.let { intent ->
                    diagnosis = intent.serializable("diagnosis")
                    diagnosis?.let { item ->
                        if (!isAdd(item)){
                            diagnosesList.add(item)
                            prescriptionDiagnoseAdapter.setData(diagnosesList)
                        }else {
                            showToast("该诊断已添加")
                        }

                    }

                }
            }
        }

    //药品回调
    private val mActivityResultLauncherDrug: ActivityResultLauncher<Intent>? =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK) {
                it.data?.let { intent ->
                    drugList = intent.serializable(KEY_DRUG_LIST)!!
                    prescriptionDrugAdapter.setData(drugList)

                }
            }
        }

    //药品加价回调
    private var onCustomBottomClick: OnCustomButtonClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(position: Int, msgType: String?) {
            val item = drugList[position]
            var num = item.num.toInt()
            when (msgType) {
                "MinusSign" -> {
                    if (num > 1) num--
                    item.num = num.toString()
                    prescriptionDrugAdapter.notifyItemChanged(position)
                }

                "plusSign" -> {
                    num++
                    item.num = num.toString()
                    prescriptionDrugAdapter.notifyItemChanged(position)
                }

                "delete" -> {
                    drugList.remove(drugList[position])
                    prescriptionDrugAdapter.setData(drugList)
                }
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        rxId = intent.getStringExtra("id")
        prescriptionDiagnoseAdapter = PrescriptionDiagnoseAdapter()
        prescriptionDrugAdapter = PrescriptionDrugAdapter(1)
        prescriptionDrugAdapter.setCustomBottomClick(onCustomBottomClick)
        mBinding.rcyDiagnosis.apply {
            val layoutFelManager = FlexboxLayoutManager(context)
            layoutFelManager.flexWrap = FlexWrap.WRAP // 按正常方向换行
            layoutFelManager.flexDirection = FlexDirection.ROW // 水平方向
            layoutFelManager.justifyContent = JustifyContent.FLEX_START // 左对齐
            layoutManager = layoutFelManager
            adapter = prescriptionDiagnoseAdapter
        }
        mBinding.rcyDrugs.apply {
            itemAnimator?.changeDuration = 0
            layoutManager = LinearLayoutManager(this@AppendTemplateActivity)
            addItemDecoration(NormalItemDecoration().apply {
                setBounds(top = dpToPx(1), bottom = dpToPx(1))
                setLastBottom(true)
                setFirstHeadMargin(true)
            })
            adapter = prescriptionDrugAdapter
        }

    }

    override fun initData() {
        rxId?.let {
            mBinding.tvTitleBar.setMiddleText("编辑处方模板")
            mBinding.tvTitleBar.getRightTextView().apply {
                text = "删除"
                visible()
                onClick {
                    CommonMessageDialog.Builder(this@AppendTemplateActivity)
                        .setTitle(getStringFromResource(R.string.dialog_tips_title))
                        .setMessage("是否确认删除当前模板？")
                        .setConfirm(getStringFromResource(R.string.default_confirm))

                        .setCancel(getString(com.compass.framework.R.string.default_cancel))
                        .setonCancelListener {
                            it?.dismiss()
                        }
                        .setonConfirmListener {
                            prescribeViewModel.deleteTemplate(rxId)
                            it?.dismiss()
                        }.create().show()

                }

            }
            showLoading()
            prescribeViewModel.getTemplateDetails(rxId, "2")
        } ?: kotlin.run {
            mBinding.tvTitleBar.getRightTextView().gone()
            mBinding.tvTitleBar.setMiddleText("添加处方模板")
        }
        prescribeViewModel.deleteLiveData.observe(this) {
            if (it){
                LiveDataBus.get().with(REFRESH_RX_TEMPLATE).postValue(REFRESH_RX_TEMPLATE)
                finish()
            }
        }

        prescribeViewModel.createLiveData.observe(this) {
            dismissLoading()
            it?.let {
                showToast("模板创建成功")
                LiveDataBus.get().with(REFRESH_RX_TEMPLATE).postValue(REFRESH_RX_TEMPLATE)
                finish()
            }
        }
        prescribeViewModel.updateLiveData.observe(this) {
            dismissLoading()
            if (it) {
                showToast("模板更新成功")
                LiveDataBus.get().with(REFRESH_RX_TEMPLATE).postValue(REFRESH_RX_TEMPLATE)
                finish()
            }

        }
        prescribeViewModel.templateDetailsLiveData.observe(this) {
            dismissLoading()
            setTemplateInfo(it)
        }
    }


    override fun intListener() {
        mBinding.tvAddDiagnosis.onClick {
            requestType = 1
            val intent = Intent(this, DiagnoseActivity::class.java)
            intent.putExtra(KEY_CONSULT_TYPE, "1")
            mActivityResultLauncherDiagnosis?.launch(intent)
        }
        mBinding.tvAddDrugs.onClick {
            requestType = 2
            val intent = Intent(this, AddDrugActivity::class.java)
            intent.putExtra(KEY_CONSULT_TYPE, requestType)
            intent.putExtra(KEY_DRUG_LIST,drugList)
            mActivityResultLauncherDrug?.launch(intent)
        }

        prescriptionDiagnoseAdapter.onItemClickListener = { _, position ->
            diagnosesList.remove(diagnosesList[position])
            prescriptionDiagnoseAdapter.setData(diagnosesList)
        }

        mBinding.edtTemplateName.addTextChangedListener {
            it?.let {
                rxInformation.name = it.toString().trim()
            }
        }
        mBinding.tvSave.onClick {

            if (rxInformation.name.isEmpty()) {
                showToast("请输入模板名称")
                return@onClick
            }
            if (diagnosesList.isNullOrEmpty()) {
                showToast("请先选择临床诊断")
                return@onClick
            }
            if (drugList.isNullOrEmpty()) {
                showToast("请添加药品信息")
                return@onClick
            }
            rxInformation.drugs = drugList
            rxInformation.diagnosis = diagnosesList
            showLoading()
            rxId?.let {
                //更新
                rxInformation.id = it
                prescribeViewModel.templateUpdate(rxInformation)
            } ?: kotlin.run {
                //创建
                prescribeViewModel.templateCreate(rxInformation)
            }
        }


    }

    private fun isAdd(diagnosis: Diagnosis):Boolean{
        for (item in diagnosesList){
            if (item.id==diagnosis.id){
                return true
            }
        }
        return false
    }

    private fun isAddDrug(drug: Drug):Boolean{
        for (item in drugList){
            if (item.name==drug.name){
                return true
            }
        }
        return false
    }

    /**
     * 设置模板信息
     */
    private fun setTemplateInfo(templateDetails: TemplateDetails?) {
        templateDetails?.let { details ->
            mBinding.edtTemplateName.setText(details.name)
            details.diagnosis?.let { list ->
                diagnosesList.addAll(list)
                prescriptionDiagnoseAdapter.setData(diagnosesList)
            }

            details.drugs?.let { drugs ->
                drugList.addAll(drugs)
                prescriptionDrugAdapter.setData(drugList)
            }

        }
    }
}